package com.koron.ticket.work.logicticket.hightask;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.koron.bean.base.Response;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.FastJsonUtils;
import com.koron.ticket.utils.StringUtils;
import com.koron.ticket.work.common.bean.FifteenTables;
import com.koron.ticket.work.common.bean.TicketBaseMsg;
import com.koron.ticket.work.common.service.FifteenTablesService;
import com.koron.ticket.work.common.service.OrderChangeStatusService;
import com.koron.ticket.work.common.service.YcCommonService;
import com.koron.ticket.work.enums.TicketNodeStatus;
import com.koron.ticket.work.enums.TicketStatus;
import com.koron.ticket.work.enums.WorkFlowType;
import com.koron.ticket.work.logicticket.hightask.bean.HighTaskDto;
import com.koron.ticket.work.logicticket.hightask.bean.YcHightaskTicketPrint;
import com.koron.ticket.work.workPermit.bean.WorkPermit;
import com.koron.ticket.work.workPermit.service.WorkPermitService;
import com.koron.ticket.work.workend.bean.WorkEnd;
import com.koron.ticket.work.workflow.bean.WorkFlow;
import com.koron.ticket.work.workflow.service.WorkFlowService;
import com.koron.ticket.work.workticket.bean.WorkTicket;
import com.koron.ticket.work.workticket.service.WorkTicketService;
import com.koron.ticket.work.workycinfo.bean.TicketYcInfoBean;
import com.koron.ticket.work.workycinfo.service.WorkYcInfoService;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;

@Service
public class HighTaskService {

    @Autowired
    private FifteenTablesService fifteenTablesService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private WorkTicketService workTicketService;

    @Autowired
    private WorkPermitService workPermitService;

    @Autowired
    private WorkYcInfoService workycinfoservice;

    @Autowired
    private YcCommonService yccommonservice;

    // 变更工单状态
    @Autowired
    private OrderChangeStatusService orderChangeStatusService;

    @TaskAnnotation("writeSave")
    public Response writeSave(SessionFactory factory, HighTaskDto dto) {
        workTicketService.checkTimeOut(factory, dto.getId(), dto.getUpdateTime());//检查信息是否过期
        String id = CodeTools.getCode32();

        // 工作票主表
        WorkTicket workticket = Convert.convert(WorkTicket.class, dto);
        // 高处作业票
        TicketYcInfoBean ticketycinfobean = Convert.convert(TicketYcInfoBean.class, dto);
        // 工作票基础信息
        TicketBaseMsg ticketbasemsg = Convert.convert(TicketBaseMsg.class, dto);

        ticketycinfobean.setTicketType(workticket.getType());
        if (StrUtil.isNotBlank(workticket.getId())) {
            workTicketService.update(factory, workticket);
            ticketycinfobean.setWorkTicketId(workticket.getId());
        } else {
            workticket.setId(id);
            workticket.setStatus(TicketNodeStatus.WRITE.getStatus());
            ticketycinfobean.setWorkTicketId(id);
            workTicketService.insert(factory, workticket);
        }
        ticketycinfobean.setProposer(dto.getDirector()); // 申请人
        ticketycinfobean.setProposerName(dto.getDirectorName());
        workycinfoservice.save(factory, ticketycinfobean);

        // 更新工作票基础信息
        yccommonservice.updateTicketMsg(factory, workticket.getId(), ticketbasemsg);

        return Response.success(workticket.getId());
    }

    @TaskAnnotation("getPrintData")
    public List<YcHightaskTicketPrint> getPrintData(SessionFactory factory, String id) {
        List<YcHightaskTicketPrint> result = yccommonservice.getPrintData(factory, id);
        return result;
    }

    @TaskAnnotation("writeSubmit")
    public Response writeSubmit(SessionFactory factory, HighTaskDto dto) {
        WorkTicket workticket = Convert.convert(WorkTicket.class, dto);
        String workTicketId = yccommonservice.ycWriteSubmitByWorkFlowType(factory, workticket, WorkFlowType.HighTaskTicketWork.getWorkFlow());
        return Response.success(workTicketId);
    }

    @TaskAnnotation("signSave")
    public Response signSave(SessionFactory factory, WorkFlow workFlow) {
        yccommonservice.signSave(factory, workFlow);
//        fifteenTablesService.signOrCountersignOrAcceptSave(factory, workFlow);
        return Response.success("提交/保存成功");
    }

    @TaskAnnotation("countersignSave")
    public Response countersignSave(SessionFactory factory, WorkFlow workFlow) {
        yccommonservice.countersignSave(factory, workFlow);
//        fifteenTablesService.signOrCountersignOrAcceptSave(factory, workFlow);
        return Response.success("提交/保存成功");
    }

    @TaskAnnotation("acceptSave")
    public Response acceptSave(SessionFactory factory, WorkFlow workFlow) {
        yccommonservice.acceptSave(factory, workFlow);
//        fifteenTablesService.signOrCountersignOrAcceptSave(factory, workFlow);
        return Response.success("提交/保存成功");
    }

    @TaskAnnotation("permitSave")
    public Response permitSave(SessionFactory factory, WorkPermit workPermit) {
        yccommonservice.permitSave(factory, workPermit);
        return Response.success("待许可-提交/保存成功");
    }

    @TaskAnnotation("ticketEndSave")
    public Response ticketEndSubmitOrSave(SessionFactory factory, WorkFlow workFlow) {
        yccommonservice.ticketEndSave(factory, workFlow);
        return Response.success("工作票待终结-提交/保存成功");
    }

    @TaskAnnotation("workflowUpdate")
    public Response workflowUpdate(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        Integer operation = redirectQuery.getOperation();
        String workTicketId = redirectQuery.getDataId();
        WorkTicket workTicket = workTicketService.queryById(factory, workTicketId);
        // 提交前状态
        Integer status = workTicket.getStatus();
        String type = workTicket.getType();

        // 1. 如果被驳回，返回对应状态，仅删除签名的数据，其他的数据不做处理
        if (operation == 1) {
            String rejectNodeCode = redirectQuery.getRejectNodeCode();
            rejectNodeCode = rejectNodeCode.replace("call-", "");
            if (rejectNodeCode.equals(TicketNodeStatus.WRITE.getNodeName())) {
                Integer rejectStatus = TicketStatus.WRITE.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.SIGN.getNodeName())) {
                Integer rejectStatus = TicketStatus.SIGN.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.COUNTERSIGN.getNodeName())) {
                Integer rejectStatus = TicketStatus.COUNTERSIGN.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.ACCEPT.getNodeName())) {
                Integer rejectStatus = TicketStatus.ACCEPT.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
                workTicket.setStatus(rejectStatus);
            } else if (StrUtil.contains(rejectNodeCode, TicketNodeStatus.PERMIT.getNodeName())) {
                // 高处作业有两个许可，平台返回的code 包含PERMIT都认为是许可节点
                Integer rejectStatus = TicketStatus.PERMIT.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                // 20211111: 如何是待许可状态，讲预览标志设置成未预览
                workTicket.setPreviewFlag(1);
                workTicket.setStatus(rejectStatus);
            } else if (rejectNodeCode.equals(TicketNodeStatus.WORK_END.getNodeName())) {
                Integer rejectStatus = TicketStatus.WORK_END.getStatus();
                fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
                workTicket.setStatus(rejectStatus);
            }
            workTicketService.update(factory, workTicket);
        } // 2. 如果通过，工作票进入下一个状态，并根据状态的不同进行不同的操作
        else if (operation == 32) {
            // 下一个节点编码
            String curNodeCode = redirectQuery.getCurNodeCode();
            curNodeCode = curNodeCode.replace("call-", "");
            String formVariables = redirectQuery.getFormVariables();
            if (status.equals(TicketStatus.WRITE.getStatus())) {
                workTicket.setStatus(2);
            }
            // 2.1 如果是签发状态，保存签名信息
            if (status.equals(TicketStatus.SIGN.getStatus())) {
                fifteenTablesService.saveWorkFLow(factory, formVariables);
                // 生成工作票号
                if (StrUtil.isBlank(workTicket.getCode())) {
                    String code = fifteenTablesService.getLastCodeByUnitAndTicketTypeNew(factory, workTicket.getUnit(), type);
                    if (StringUtils.isEmpty(code)) {
                        return Response.fail("工作票票号生成有问题，请联系运维人员");
                    }
                    workTicket.setCode(code);
                }
                workTicket.setStatus(4);//放弃自增控制，改为手动控制
            }
            // 2.3 如果是待接收状态：1.保存签名信息；2.将预览标志设为未预览
            else if (status.equals(TicketStatus.ACCEPT.getStatus())) {
                // 保存签名信息
                fifteenTablesService.saveWorkFLow(factory, formVariables);
                // 将预览标志设为未预览
                workTicket.setPreviewFlag(1);
                workTicket.setStatus(5);//放弃自增控制，改为手动控制
            }
            // 2.4 如果是待许可状态，保存签名信息，以及待许可信息
            else if (status.equals(TicketStatus.PERMIT.getStatus())) {
                // 保存许可信息
                WorkPermit workPermit = JSONObject.parseObject(formVariables, WorkPermit.class);
                // 保存签名信息
                List<WorkFlow> workFlowList = workPermit.getWorkFlowList();
                if (CollUtil.isNotEmpty(workFlowList)) {
                    for (WorkFlow workFLow : workFlowList) {
                        workFLow.setId(workFLow.getWorkFlowId());
                        workFlowService.save(factory, workFLow);
                    }
                }
                if(curNodeCode.equals(TicketNodeStatus.PERMIT2.getNodeName())){
                    workTicket.setStatus(5);//放弃自增控制，改为手动控制
                }
                if(curNodeCode.equals(TicketNodeStatus.TICKET_END.getNodeName())){
                    workTicket.setStatus(7);//放弃自增控制，改为手动控制
                }
            }
            workTicketService.update(factory, workTicket);
        } else if (operation == 256) {
            Integer rejectStatus = TicketStatus.WRITE.getStatus();
            fifteenTablesService.clenWorkFlowByStatus(factory, workTicketId, rejectStatus);
            workPermitService.deleteByWorkTicketId(factory, workTicketId);//删除许可信息
            workTicket.setStatus(rejectStatus);
            workTicketService.update(factory, workTicket);
        } else {
            return Response.fail("操作类型为：" + operation + ",请联系运维人员");
        }

        return Response.success("高处作业票提交成功");
    }

    @TaskAnnotation("workflowUpdateEnd")
    public Response workflowUpdateEnd(SessionFactory factory, RedirectQuery redirectQuery) throws ParseException {
        String formVariables = redirectQuery.getFormVariables();
        WorkEnd workend = FastJsonUtils.getJsonToBean(formVariables, WorkEnd.class);
        List<WorkFlow> workFlowList = workend.getWorkFlowList();
        for (WorkFlow workFlow : workFlowList) {
            workFlow.setId(workFlow.getWorkFlowId());
            workFlowService.save(factory, workFlow);
        }
//        fifteenTablesService.saveWorkFLow(factory, formVariables);
        WorkTicket workticket = new WorkTicket();
        workticket.setId(workend.getWorkTicketId());
        workticket.setStatus(8);
        workTicketService.update(factory, workticket);
        return Response.success("工作票已归档", workend.getId());
    }

    @TaskAnnotation("workflowUpdateCancel")
    public Response workflowUpdateCancel(SessionFactory factory, RedirectQuery redirectQuery) {
        fifteenTablesService.workflowUpdateCancel(factory, redirectQuery);
        return Response.success("工作票已作废");
    }

    public void deleteById(SessionFactory factory, String id) {
        fifteenTablesService.deleteById(factory, id);
    }

    /**
     * 详情
     * @param factory
     * @param id
     * @return
     */
    public HighTaskDto getById(SessionFactory factory, String id) {
        // 主表
        WorkTicket workTicket = workTicketService.queryById(factory, id);
        // 工作票基础信息
        TicketBaseMsg ticketBaseMsg = yccommonservice.queryTicketMsg(factory, id);
        // 高处票基础信息
        TicketYcInfoBean ycInfo = workycinfoservice.getYcInfo(factory, id);
        // 签名信息
        List<WorkFlow> workFlows = workFlowService.queryByTicketId(factory, id);

        HighTaskDto dto = new HighTaskDto();
        BeanUtil.copyProperties(workTicket, dto);
        BeanUtil.copyProperties(ticketBaseMsg, dto);
        BeanUtil.copyProperties(ycInfo, dto);
        dto.setId(workTicket.getId());
        dto.setWorkFlowList(workFlows);
        return dto;
    }

    /**
     * 初始化数据
     */
    public FifteenTables add() {
        FifteenTables fifteenTables = fifteenTablesService.addByType("ElectricalFirst");
        return fifteenTables;
    }


}
